package com.onemore.cc.net_frame.callback;

import android.util.Log;

import com.google.gson.Gson;
import com.onemore.cc.net_frame.exception.ExceptionEngine;
import com.onemore.cc.net_frame.http.Response;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Create by lizihao
 * Desc:
 * Date: 2018/10/9
 */
public abstract class HCallBack<T> extends HttpCallback<T> {
    public HCallBack() {
        Log.i("lln","HCallback");
    }

    private Type type;

    @Override
    public void inSuccess(T t) {
        onSuccess(parse((String) t));
    }

    @Override
    public void inError(int code, String desc) {
        onError(code, desc);
    }

    @Override
    public void inCancel() {
        onCancel();
    }

    @Override
    public T parse(String data) {
        Log.i("lln","data=="+data);
        T t = null;
        try {
            Response response = new Gson().fromJson(data, Response.class);
            if (response.isSuccess()) {
                if (response.getResult() != null) {
                    t = getGeneric(response.getResult().toString());
                } else {
                    onNoneData(ExceptionEngine.DATA_NONE, "没有查到更多数据");
                }
            }
        } catch (Exception e) {
            onError(ExceptionEngine.ANALYTIC_CLIENT_DATA_ERROR, "解析数据出错");
        }


        return t;
    }

    /**
     * 成功回调
     *
     * @param value
     */
    public abstract void onSuccess(T value);

    /**
     * 失败回调
     *
     * @param code
     * @param desc
     */
    public abstract void onError(int code, String desc);

    /**
     * code=0 但是data=null
     *
     * @param code
     * @param desc
     */
    public abstract void onNoneData(int code, String desc);

    /**
     * 取消回调
     */
    public abstract void onCancel();

    /**
     * 自动解析json至回调中的JavaBean
     *
     * @param jsonData //     * @param callBack
     * @param <T>
     * @return
     */
    private <T> T getGeneric(String jsonData) {
        Gson gson = new Gson();
        //通过反射获取泛型的实例
        Type genertypt = getClass().getGenericSuperclass();//获得所有带有泛型的父类
        //判断是否带有泛型
        if (genertypt instanceof ParameterizedType) {
            //获取参数化类型的数组
            Type[] p = ((ParameterizedType) genertypt).getActualTypeArguments();
            type = p[0];
        }
        T t = gson.fromJson(jsonData, type);//通过gson转到对应的JavaBean
        Log.i("lln", "ttttt");
        return t;
    }
}
